import './style/index.less';
import classNames from 'classnames';
import * as React from 'react';
import { ConfigContext } from '../config-provider';
import Item from './Item';

export type SpaceSize = number;

export interface SpaceProps extends React.HTMLAttributes<HTMLDivElement> {
  prefixCls?: string;
  className?: string;
  rootClassName?: string;
  style?: React.CSSProperties;
  size?: SpaceSize | [SpaceSize, SpaceSize];
  direction?: 'horizontal' | 'vertical';
  align?: 'start' | 'end' | 'center' | 'baseline';
  split?: React.ReactDOM;
  wrap?: boolean;
}

export const SpaceContext = React.createContext({
  latestIndex: 0,
  horizontalSize: 0,
  verticalSize: 0,
  supportFlexGap: false,
});

const spaceSize = {
  small: 8,
  middle: 16,
  large: 24,
};

function getNumberSize(size: SpaceSize) {
  return typeof size === 'string' ? spaceSize[size] : size || 0;
}

const Space: React.FC<SpaceProps> = (props) => {
  const { getPrefixCls, space } = React.useContext(ConfigContext);
  const prefixCls = getPrefixCls('space');

  const {
    size = space?.size || 'small',
    align,
    className,
    rootClassName,
    children,
    direction = 'horizontal',
    prefixCls: customizePrefixCls,
    split,
    style,
    wrap = false,
    ...otherProps
  } = props;

  const cn = classNames(prefixCls);

  const itemClassName = `${prefixCls}-item`;

  const childNodes = React.Children.toArray(children);
  console.log('childNodes', childNodes);
  let latestIndex = 0;
  const nodes = childNodes.map((child, i) => {
    if (child !== null && child !== undefined) {
      latestIndex = i;
    }
    const itemClassName = `${prefixCls}-item`;
    const key = (child && child.key) || `${itemClassName}-${i}`;

    const gapStyle: React.CSSProperties = {};

    return <Item key={key} className={itemClassName}>{child}</Item>;
  });

  if (childNodes.length === 0) {
    return null;
  }

  const gapStyle: React.CSSProperties = {};

  if (wrap) {
  }

  const [horizontalSize, verticalSize] = React.useMemo(
    () =>
      (
        (Array.isArray(size) ? size : [size, size]) as [SpaceSize, SpaceSize]
      ).map((item) => getNumberSize(item)),
    [size],
  );

  gapStyle.columnGap = horizontalSize;
  gapStyle.rowGap = verticalSize;

  return (
    <div
      className={cn}
      style={{
        ...gapStyle,
        ...style,
      }}
    >
      {nodes}
    </div>
  );
};

export default Space;
